/*
   winmain.cxx
*/

#define _WIN32_WINNT 0x0501

#include <stdio.h>
#include <windows.h>

#include <commctrl.h>
#pragma comment(lib, "comctl32.lib")

#include <mmsystem.h>
#pragma comment(lib, "winmm.lib")

#include <shlwapi.h>
#pragma comment(lib, "shlwapi.lib")

#include "mainwin.h"

char homedirectory[MAX_PATH];

HRESULT (STDAPICALLTYPE *SetWindowTheme)(HWND, LPCWSTR, LPCWSTR);

CRITICAL_SECTION cs;

#define DURATION 100 //msec

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int)
{
  MSG msg;
  mainWin *mainwin=NULL;

  HANDLE hmutex=CreateMutex(NULL, FALSE, MAINWIN_CLASS_NAME);
  DWORD errorCode=GetLastError();
  if((hmutex==NULL)||(errorCode==ERROR_ALREADY_EXISTS)||(errorCode==ERROR_INVALID_HANDLE)){
    HWND alternate_hwnd=FindWindow(MAINWIN_CLASS_NAME, NULL);
    if(alternate_hwnd!=NULL) SetForegroundWindow(alternate_hwnd);
    goto app_end;
  }

  SetWindowTheme=NULL;
  HMODULE hDll=LoadLibrary("uxtheme");
  if(hDll){
    SetWindowTheme=(HRESULT(STDAPICALLTYPE *)(HWND, LPCWSTR, LPCWSTR))
      GetProcAddress(hDll, "SetWindowTheme");
  }

  GetModuleFileName(NULL, homedirectory, MAX_PATH);
  PathRemoveFileSpec(homedirectory);
  SetCurrentDirectory(homedirectory);

  timeBeginPeriod(1);
  InitializeCriticalSectionAndSpinCount(&cs, 4000);

  INITCOMMONCONTROLSEX icex;
  icex.dwSize=sizeof(INITCOMMONCONTROLSEX);
  icex.dwICC=ICC_COOL_CLASSES|ICC_WIN95_CLASSES;
  InitCommonControlsEx(&icex);

  mainwin=new mainWin(hInstance);
  
  BOOL done=FALSE;
  DWORD next=timeGetTime()+DURATION;
  
  while(!done){
    if(PeekMessage(&msg,0, 0, 0, PM_NOREMOVE)){
      if(msg.message==WM_QUIT){
        done=TRUE;
      }else if(GetMessage(&msg, NULL, 0, 0)>0){
        TranslateMessage(&msg);
        DispatchMessage(&msg);
      }
    }else{
      if(timeGetTime()>=next){
        next=timeGetTime()+DURATION;
        //
      }
      if(next-timeGetTime()>0){
        MsgWaitForMultipleObjects(0, NULL, FALSE, next-timeGetTime(), QS_ALLINPUT);
      }
    }
  }

 winend:
  delete mainwin;

 app_end:
  if(hmutex!=NULL) CloseHandle(hmutex);

  DeleteCriticalSection(&cs);
  return 0;
}

